<?php
namespace app\index\controller;

use think\Controller;
use think\Session;

class Cash extends Controller
{
    public function _initialize()
    {
        $id = session('user');

        if (!$id) {
            $this->redirect('login/login/index');
        }
    }
	
    /**
     * 获取提现申请列表
     * @author 秋水
     * @DateTime 2018-12-28T15:10:04+0800
     */
    public function index()
    {
        $code       =   input('code');
        $msg        =   input('msg');

        $list = db('cash')->order('status asc,create_time desc')->paginate(12);
        $users = [];
        foreach ($list as $key => $o) {
            $users[$o['uid']] = db('user')->where(['id'=>$o['uid']])->find();
        }
        return view('index',[
            'msg'   =>  $msg,
            'list'  =>  $list,
            'users' => $users,
            'code'  =>  $code
        ]);
    }

    public function update()
    {
        $code   =   input('msg');
        $data   =   db('cash')->where('id',input('id'))->find();
        $userAuth = db('user_auth')->where(['uid'=>$data['uid']])->find();
        $cashrate = db('todo_config')->where(['title'=>'cashrate'])->find();
        return view('update',
            [
                'data'  =>  $data,
                'user_auth' => $userAuth,
                'code'  =>  $code,
                'cashrate' => $cashrate['value'],
            ]);
    }

    /**
     * 提现操作
     * @author 秋水
     * @DateTime 2018-12-28T16:32:58+0800
     */
    public function edit()
    {
        $status = input('status');
        $insert['status'] = $status;
        $insert['refuse_reason'] = input('refuse_reason');
        $id = input('id');
        if($status == 3) {
            // 驳回提现申请，返还积分
            $cashData = db('cash')->where(['id'=>$id])->find();
            $user = db('user')->where(['id'=>$cashData['uid']])->find();
            $updateData = [
                'money' => $user['money']+$cashData['money'],
                'cashamount' => $user['cashamount']+$cashData['money']
            ];
            db('user')->where(['id'=>$cashData['uid']])->update($updateData);
        } else if($status == 2) {
            // 增加提现记录
            $cashData = db('cash')->where(['id'=>$id])->find();
            $financeLogData = [
                'uid' => $cashData['uid'],
                'amount' => $cashData['money'],
                'type' => 6,
                'changetime' => time(),
            ];
            db('todo_finance')->insert($financeLogData);
        }
        $r = db('cash')->where(['id'=>$id])->update($insert);
        if($r!==false)
        {
            return redirect('cash/index',['code'=>1,'msg'=>'添加成功']);
        }else{
            unlink($url);
            return;
        }
    }
}